package com.ohuang.wallpapermanager.storage.storage

import android.util.Log
import com.google.gson.reflect.TypeToken
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.Json.Default.serializersModule
import kotlinx.serialization.serializer
import java.lang.reflect.Type

class KotlinJsonSpStorage<T : Any>(val transform: KotlinJsonSpStorageTransform<T>, var iStorage: SpStorage<String>, var defaultObject:T) : IStorage<T> {
    override fun getValue(): T {
        var value = iStorage.getValue()
        value = value.ifEmpty { transform.toJson(defaultObject) }
        return transform.fromJson(value)
    }

    override fun setValue(value: T) {
        iStorage.setValue(transform.toJson(value))
    }
}
 interface  KotlinJsonSpStorageTransform<T>{

     fun toJson(value:T):String
     fun fromJson(value:String):T
 }


inline fun <reified T : Any> SpStorageUtil.getForKotlinJson(key: String, default: T): IStorage<T> {
    val json=Json{
        ignoreUnknownKeys = true
    }
    val obj=object :KotlinJsonSpStorageTransform<T>{
        override fun toJson(value: T): String {
            return json.encodeToString(serializersModule.serializer(),value)
        }

        override fun fromJson(value: String): T {
         return json.decodeFromString(value)
        }

    }

    return KotlinJsonSpStorage(obj, get<String>(key,""),default)
}
